<template>
    <div class="tab-content">
        <!-- 操作按钮 -->
        <div class="operation-bar">
            <el-button type="primary" @click="openAddDialog">添加站点数据</el-button>
        </div>
        
        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" class="data-table">
            <el-table-column prop="siteName" label="站点名称" width="200" />
            <el-table-column prop="cabinetStatus" label="电柜状态" >
                <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.cabinetStatus)">{{ getPointTypeName(scope.row.cabinetStatus) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="count" label="次数"  />
            <el-table-column prop="fullBatteryCount" label="满电数"  />
            <el-table-column label="操作" width="250">
                <template #default="scope">
                    <el-button size="small" @click="editRow(scope.row, scope.$index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteRow(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 添加/编辑弹框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="dialogTitle" 
            width="500px"
            @close="resetForm"
        >
            <el-form 
                ref="formRef" 
                :model="formData" 
                :rules="formRules" 
                label-width="100px"
            >
                <el-form-item label="站点名称" prop="siteName">
                    <el-input v-model="formData.siteName" placeholder="请输入站点名称" />
                </el-form-item>
                <el-form-item label="电柜状态" prop="cabinetStatus">
                     <el-select v-model="formData.cabinetStatus" placeholder="请选择电柜状态" style="width: 100%">
                        <el-option label="正常" value="success" />
                        <el-option label="故障" value="danger" />
                        <el-option label="维护中" value="warning" />
                        <el-option label="离线" value="info" />
                     </el-select>
                 </el-form-item>
                <el-form-item label="次数" prop="count">
                    <el-input-number 
                        v-model="formData.count" 
                        :min="0" 
                        placeholder="请输入次数"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="满电数" prop="fullBatteryCount">
                    <el-input-number 
                        v-model="formData.fullBatteryCount" 
                        :min="0" 
                        :max="11"
                        placeholder="请输入满电数"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { updateDataClassify } from '@/api/port'


// 表格数据
const tableData = ref<Array<{
    siteName: string
    cabinetStatus: string
    count: number
    fullBatteryCount: number,
}>>([])

// 弹框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加站点数据')
const isEdit = ref(false)
const editIndex = ref(-1)

// 表单数据
const formData = reactive({
    siteName: '',
    cabinetStatus: '',
    count: 0,
    fullBatteryCount: 0
})
// 数字范围验证函数
const validateNumber = (rule: any, value: number, callback: (error?: Error) => void) => {
    if (value === null || value === undefined) {
        callback(new Error('请输入数字'))
    } else if (value < 0) {
        callback(new Error('请输入大于等于0的数字'))
    } else if (value > 1000000) {
        callback(new Error('请输入小于等于1000000的数字'))
    } else {
        callback()
    }
}

const validateNumberTwo = (rule: any, value: number, callback: (error?: Error) => void) => {
    if (value === null || value === undefined) {
        callback(new Error('请输入数字'))
    } else if (value < 0) {
        callback(new Error('请输入大于等于0的数字'))
    } else if (value > 12) {
        callback(new Error('满电数必须在0-11之间'))
    } else {
        callback()
    }
}
// 表单验证规则
const formRules: FormRules = {
    siteName: [
        { required: true, message: '请输入站点名称', trigger: 'blur' },
        { min: 2, max: 50, message: '站点名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    cabinetStatus: [
        { required: true, message: '请选择电柜状态', trigger: 'change' }
    ],
    count: [
        { required: true, message: '请输入次数', trigger: 'blur' },
        { validator: validateNumber, trigger: 'blur' }
    ],
    fullBatteryCount: [
        { required: true, message: '请输入满电数', trigger: 'blur' },
        { validator: validateNumberTwo, trigger: 'blur' }
    ]
}

const formRef = ref<FormInstance>()

// 获取状态标签类型
const getStatusTagType = (status: string) => {
    switch (status) {
        case '正常':
            return 'success'
        case '故障':
            return 'danger'
        case '维护中':
            return 'warning'
        case '离线':
            return 'info'
        default:
            return ''
    }
}
// 获取点位类型名称
const getPointTypeName = (type: string) => {
    const nameMap: Record<string, string> = {
        success: '正常',
        danger: '故障',
        warning: '维护中',
        info: '离线'
    }
    return nameMap[type] || type
}

// 打开添加弹框
const openAddDialog = () => {
    dialogTitle.value = '添加站点数据'
    isEdit.value = false
    dialogVisible.value = true
    resetForm()
}

// 编辑行数据
const editRow = (row: any, index: number) => {
    dialogTitle.value = '编辑站点数据'
    isEdit.value = true
    editIndex.value = index
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 删除行数据
const deleteRow = (index: number) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        tableData.value.splice(index, 1)
        ElMessage.success('删除成功')
        upData()
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        siteName: '',
        cabinetStatus: '',
        count: 0,
        fullBatteryCount: 0
    })
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        
        if (isEdit.value) {
            // 编辑模式
            Object.assign(tableData.value[editIndex.value], formData)
            ElMessage.success('编辑成功')
        } else {
            // 添加模式
            tableData.value.push({ ...formData })
            ElMessage.success('添加成功')
        }
        // 调用保存接口
        upData()
        console.log('保存配送数据配置:', tableData.value)
        dialogVisible.value = false
        resetForm()
    } catch (error) {
        ElMessage.warning('请填写完整的表单信息')
    }
}

const upData = async () => {
    await updateDataClassify({
        id: 3,
        key: 'module4',
        value: tableData.value
    })
}

// 初始化函数
const init = (module: any) => {
    // 可以在这里重置表格数据或从API获取数据
    console.log('Module4 初始化')
    if(module){
        tableData.value = module
    }
}

// 暴露方法给父组件
defineExpose({
    init
})
</script>

<style scoped>
.tab-content {
    padding: 20px;
}

.operation-bar {
    margin-bottom: 20px;
}

.data-table {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>